package com.sky.service.impl;

import com.fasterxml.jackson.databind.ser.Serializers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 明文密码MD5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
//        System.out.println("password"+password);

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**新增员工功能
     * @param employeeDTO
     */
    public void addEmp(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();

        //拷贝DTO中相同属性到employee对象
        BeanUtils.copyProperties(employeeDTO,employee);

        //补全其他属性
        //1.状态
        employee.setStatus(StatusConstant.ENABLE);

        //2.默认密码  需要加密后存储
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //3.日期
//        employee.setCreateTime(LocalDateTime.now());     //使用公共字段填充了
//        employee.setUpdateTime(LocalDateTime.now());

        //4.创建人id,修改人id
        /**
         * 拦截器在验证请求者时会解析JW令牌token，从中解析出请求者id，并传入下面的两个参数
         */
//        默认创建人id和修改人id需要完善  ,通过线程id传递   在拦截器中定义线程id的设置
        Long currentId = BaseContext.getCurrentId();

//        employee.setUpdateUser(currentId);           //使用公共字段填充了
//        employee.setCreateUser(currentId);

        employeeMapper.insert(employee);
    }

    @Override
    public PageResult PageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //基于数据库的分页查询 select * from employee limit 0,10  ,可以通过pagehelper进行简化操作
        //开始分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());

        Page<Employee> pages = employeeMapper.pageQuery(employeePageQueryDTO);
        long total = pages.getTotal();
        List<Employee> result = pages.getResult();

        return new PageResult(total,result);
    }

    /**
     * 启用或禁用员工账号
     * @param status
     * @param id
     */
    public void TurnEmp(Integer status, Long id) {

        Employee employee = new Employee();
        employee.setStatus(status);
        employee.setId(id);

        employeeMapper.update(employee);

    }

    /**
     * 修改员工信息。已经实现过了update，所以直接创建一个对象进行方法调用即可
     * @param employeeDTO
     */
    public void editEmp(EmployeeDTO employeeDTO) {

//        Employee employee = Employee.builder()
//                .id(employeeDTO.getId())
//                .idNumber(employeeDTO.getIdNumber())
//                .build();

        //使用工具类
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);

        //补充属性和更新时间
//        employee.setUpdateTime(LocalDateTime.now());          //使用公共字段填充了

        //拦截器中使用线程定义了当前的用户id
        Long currentId = BaseContext.getCurrentId();
//        employee.setUpdateUser(currentId);

        employeeMapper.update(employee);  //已经统一实现了
    }

    public Employee list(Long id) {
        Employee employee = new Employee();
        employee = employeeMapper.List(id);
        employee.setPassword("**********");   //更保险
        return employee;
    }


}
